import userTempId from "@/utils/userTempId";
import {
  getItem,
  setItem,
  removeItem
} from "@/utils/localStorage";
import {
  reqLogin,
  reqUserMessage
} from "@/api";

const state = {
  userTempId: userTempId(),
  token: getItem("token") || "",

  //userMessage始终是一个对象
  userMessage: {},
};

const mutations = {
  //设置token
  set_Token(state, payload) {
    state.token = payload.token;
    //永久化存储token
    setItem("token", payload.token);
  },

  //设置用户信息
  set_UserMessage(state, payload) {
    state.userMessage = payload.userMessage;
  },

  //删除token，否则无法进入登录页面
  remove_Token(state) {
    //这一步删除token
    state.token = "";

    //删除本地token
    removeItem("token");
    //清理用户信息
    state.userMessage = {};
  }
};

const actions = {
  async getToken({
    commit
  }, userInfo) {
    const result = await reqLogin(userInfo);
    commit("set_Token", {
      token: result.token
    });
  },

  async getUserMessage({
    commit
  }) {
    const result = await reqUserMessage();
    commit("set_UserMessage", {
      userMessage: result
    })
  },
};

const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};